package com.szit.test.servlet;

import com.szit.test.biz.UserBiz;
import com.szit.test.biz.impl.UserBizImpl;
import com.szit.test.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 获取用户名称密码参数值
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));

        // 调用业务逻辑层
        UserBiz ubiz = new UserBizImpl();
        int flag = ubiz.login(user);

        // 判断
        if(flag == 1) {
            // 保存用户登录会话
            request.getSession().setAttribute("loginUser",user);
            // 跳转到首页
            response.sendRedirect("index.jsp");
        } else if(flag == -1){
            request.setAttribute("error","用户名不存在，请重新输入！");
            request.setAttribute("tempUser",user);
            request.getRequestDispatcher("login.jsp").forward(request,response);
        } else {
            request.setAttribute("error","密码不正确，请重新输入！");
            request.setAttribute("tempUser",user);
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }
}
